<template>
  <div class="personalClueDataStyle">
    <!-- 搜索条件 -->
    <div class="formStyle">
      <RadioGroup v-model="formInline.time" type="button" @on-change="timeFun">
        <Radio label="今天"></Radio>
        <Radio label="昨日"></Radio>
        <Radio label="最近7天"></Radio>
        <Radio label="本周"></Radio>
        <Radio label="上周"></Radio>
        <Radio label="本月"></Radio>
      </RadioGroup>
      <span class="spanMarginRL">日期选择：</span><DatePicker type="daterange" placement="bottom-end" v-model="formInline.date" placeholder="请选择日期范围" style="width: 220px" @on-change="dateFun"></DatePicker>
    </div>
    <div class="formStyle">
      <Row>
        <Col span="12">
          <span class="spanMargin">渠道名称：</span>
          <Select v-model="formInline.realEstate" style="width:200px;" placeholder="请选择渠道名称" filterable>
            <template v-for="(item, index) in realEstateList">
              <Option v-for="(items, indexs) in item.list" :value="items.channelId" :key="items.channelId">{{ items.channelName +"-"+ items.provinceName +"-"+ items.cityName}}</Option>
            </template>
          </Select>
        </Col>
        <Col span="12">
          <Button type="primary" style=" width: 80px;" @click="queryFun">查 询</Button>
          <Button style=" width: 80px; margin: 0 10px;" @click="emptyFun">重 置</Button>
          <Button type="primary" :disabled="data1.length > 0 ? false : true" style=" width: 80px;" @click="exportFun">导 出</Button>
        </Col>
      </Row>
    </div>
    <!-- table -->
    <Table :loading="loading" ref="TableHeight" :max-height="onresizeHeight" :columns="columns1" :data="data1" @on-sort-change="sortTableFun"></Table>
    <!-- 分页 -->
    <div class="pagePublicStyle" v-show="pageData.total > 0">
      <div class="totalCount">
        当前第 {{pageData.page}} 页，
        当前第 {{(pageData.page-1)*pageData.rows+1}} 条到第 {{pageData.page*pageData.rows>pageData.total?pageData.total:pageData.page*pageData.rows}} 条，
        共 {{pageData.total}} 条
      </div>
      <Page class="pager" :total="pageData.total" :pageSize="pageData.rows" :current="pageData.page" :page-size-opts="pageData.pageSizeOpts" @on-change="pageOnChangeFun" @on-page-size-change="pageOnPageSizeChangeFun" placement="top" show-elevator show-sizer />
    </div>
  </div>
</template>
<script>
  import { aggChannelQueryGroup, channelReport, userbuildinglist, businessuserget } from "@/api/dataManagement.js";
  import Helper from "@/common/helper.js";
  import {buildExport} from "@/common/axios"
  import tool from "@/common/tool"
  let userMess = JSON.parse(tool.getStorage('userMess'))
  export default {
    components: {

    },
    data() {
      return {
        buildingIds: [],
        loading: false,
        onresizeHeight: 0,
        pageData: {
          total: 0,
          page: 1,
          rows: 14,
          pageSizeOpts: [20, 30, 40, 50]
        },
        formInline: {
          time: '今天',
          realEstate: ''
        },
        realEstateList: [],
        sortOBj: '',
        columns1: [
          {
            title: '序号',
            type: 'index',
            width: 80,
            align: 'center'
          },
          {
            title: '渠道名称',
            key: 'channelName',
            minWidth: 220,
            render: (h, params) => {
              return h("div", [
                h(
                  "span",
                  {
                    style: {
                      display: "inline-block",
                      width: "100%",
                      overflow: "hidden",
                      textOverflow: "ellipsis",
                      whiteSpace: "nowrap"
                    },
                    domProps: {
                      title: params.row.channelName
                    }
                  },
                  params.row.channelName
                )
              ]);
            },
          },
          {
            title: '互动',
            key: 'interact',
            minWidth: 100,
            sortable: 'custom',
            render: (h, params) => {
              return h('div',  params.row.interact || '-');
            }
          },
          {
            title: '留资',
            key: 'retain',
            minWidth: 100,
            sortable: 'custom',
            render: (h, params) => {
              return h('div',  params.row.retain || '-');
            }
          },
          {
            title: '到访',
            key: 'follow_views',
            minWidth: 100,
            sortable: 'custom',
            render: (h, params) => {
              return h('div',  params.row.followViews || '-');
            }
          },
          {
            title: '认购',
            key: 'subscription',
            minWidth: 100,
            render: (h, params) => {
              return h('div',  params.row.subscription || '-');
            }
          },
          {
            title: '签约',
            key: 'SIGN',
            minWidth: 100,
            render: (h, params) => {
              return h('div',  params.row.sign || '-');
            }
          },
          {
            title: '互动留资率',
            key: 'interactRetainRate',
            minWidth: 120,
            sortable: 'custom',
            render: (h, params) => {
              return h('div',  (params.row.interactRetainRate&&params.row.interactRetainRate +'%') || '-');
            }
          },
          {
            title: '留资到访率',
            key: 'interactFollowViewsRate',
            minWidth: 120,
            sortable: 'custom',
            render: (h, params) => {
              return h('div',  (params.row.interactFollowViewsRate&&params.row.interactFollowViewsRate +'%') || '-');
            }
          },
          {
            title: '到访认购率',
            key: 'followViewsSubscriptionRate',
            minWidth: 120,
            sortable: 'custom',
            render: (h, params) => {
              return h('div', (params.row.followViewsSubscriptionRate&&params.row.followViewsSubscriptionRate +'%') || '-');
            }
          },
          {
            title: '认购签约率',
            key: 'subscriptionSignRate',
            minWidth: 120,
            sortable: 'custom',
            render: (h, params) => {
              return h('div', (params.row.subscriptionSignRate&&params.row.subscriptionSignRate +'%') || '-');
            }
          }
        ],
        data1: []
      }
    },
    methods: {
      dateFun() {
        this.formInline.time = ''
      },
      queryFun() {
        this.pageData.page = 1;
        // this.pageData.rows = 14;
        this.initData();
      },
      emptyFun() {
        this.formInline.time = '昨日'
        let timer = this.timeForMat(1)
        this.formInline.date = [timer.t2, timer.t1]
        this.formInline.realEstate = ''
        this.pageData.page = 1;
        this.sortOBj = ''
        // this.pageData.rows = 14;
        this.initData();
      },
      exportFun() {
        let params = {
          startTime: (this.formInline.date[0] && Helper.timestampToTime(this.formInline.date[0], 'date')) || '',
          endTime: (this.formInline.date[1] && Helper.timestampToTime(this.formInline.date[1], 'date')) || '',
          channelId: this.formInline.realEstate,
          buildingIds: this.buildingIds,
          sort: (this.sortOBj && this.sortOBj.order == 'normal' ? 'interact' : this.sortOBj.key) || 'interact',
          rule: (this.sortOBj && this.sortOBj.order == 'normal' ? 'desc' : this.sortOBj.order) || 'desc',
          createExcelType: 3,
          userId: userMess.appId
        }
        buildExport("渠道线索数据", '/dt-business/dataReport/down', params);
      },
      initData() {
        let params = {
          page: this.pageData.page,
          rows: this.pageData.rows,
          startTime: (this.formInline.date[0] && Helper.timestampToTime(this.formInline.date[0], 'date')) || '',
          endTime: (this.formInline.date[1] && Helper.timestampToTime(this.formInline.date[1], 'date')) || '',
          channelId: this.formInline.realEstate,
          buildingIds: this.buildingIds,
          sort: (this.sortOBj && this.sortOBj.order == 'normal' ? 'interact' : this.sortOBj.key) || 'interact',
          rule: (this.sortOBj && this.sortOBj.order == 'normal' ? 'desc' : this.sortOBj.order) || 'desc'
        }
        channelReport(params).then(res=>{
          this.loading = false
          if (res && res.list) {
            this.data1 = res.list
            this.pageData.total = Number(res.total)
            this.$nextTick(() => {
              this.onresizeHeight = window.innerHeight - this.$refs.TableHeight.$el.offsetTop - 100
            });
          } else {
            this.pageData.total = 0
            this.data1 = []
          }
        }).catch(err=>{
          this.loading = false
          this.$Message.error(err)
        })
      },
      // 分页 页码改变事件
      pageOnChangeFun(page) {
        this.pageData.page = page;
        this.initData();
      },
      // 分页 每页条数改变事件
      pageOnPageSizeChangeFun(rows) {
        this.pageData.rows = rows;
        this.pageData.page = 1;
        this.initData();
      },
      sortTableFun(parm) {
        this.sortOBj = parm
        this.pageData.page = 1;
        // this.pageData.rows = 14;
        this.initData();
      },
      timeForMat (count) {
        let time1 = new Date()
        time1.setTime(time1.getTime() - (24 * 60 * 60 * 1000))
        let Y1 = time1.getFullYear()
        let M1 = ((time1.getMonth() + 1) >= 10 ? (time1.getMonth() + 1) : '0' + (time1.getMonth() + 1))
        let D1 = (time1.getDate() >= 10 ? time1.getDate() : '0' + time1.getDate())
        let timer1 = Y1 + '-' + M1 + '-' + D1
        let time2 = new Date()
        time2.setTime(time2.getTime() - (24 * 60 * 60 * 1000 * count))
        let Y2 = time2.getFullYear()
        let M2 = ((time2.getMonth() + 1) >= 10 ? (time2.getMonth() + 1) : '0' + (time2.getMonth() + 1))
        let D2 = (time2.getDate() >= 10 ? time2.getDate() : '0' + time2.getDate())
        let timer2 = Y2 + '-' + M2 + '-' + D2
        return {
          t1: timer1,
          t2: timer2
        }
      },
      formatDate(date) {
        let myyear = date.getFullYear();
        let mymonth = date.getMonth() + 1;
        let myweekday = date.getDate();
        if (mymonth < 10) {
          mymonth = "0" + mymonth;
        }
        if (myweekday < 10) {
          myweekday = "0" + myweekday;
        }
        return (myyear + "-" + mymonth + "-" + myweekday);
      },
      getMonthDays(myMonth) {
        let now = new Date();
        let nowYear = now.getYear();
        nowYear += (nowYear < 2000) ? 1900 : 0;
        let monthStartDate = new Date(nowYear, myMonth, 1);
        let monthEndDate = new Date(nowYear, myMonth + 1, 1);
        let days = (monthEndDate - monthStartDate) / (1000 * 60 * 60 * 24);
        return days;
      },
      timeFun(val) {
        let now = new Date();
        let nowDayOfWeek = now.getDay() == 0 ? 7 : now.getDay();
        let nowDay = now.getDate();
        let nowMonth = now.getMonth();
        let nowYear = now.getYear();
        nowYear += (nowYear < 2000) ? 1900 : 0;
        if (val === '今天') {
          let timer = this.timeForMat('')
          this.formInline.date = [timer.t2, timer.t2]
        } else if (val === '昨日') {
          let timer = this.timeForMat(1)
          this.formInline.date = [timer.t2, timer.t1]
        } else if (val === '最近7天') {
          let timer = this.timeForMat(7)
          this.formInline.date = [timer.t2, timer.t1]
        } else if (val === '本周') {
          let weekStartDate = this.formatDate(new Date(nowYear, nowMonth, nowDay - nowDayOfWeek + 1));
          let weekEndDate = this.formatDate(new Date(nowYear, nowMonth, nowDay + (7 - nowDayOfWeek)));
          this.formInline.date = [weekStartDate, weekEndDate]
        } else if (val === '上周') {
          let weekStartDate = this.formatDate(new Date(nowYear, nowMonth, nowDay - nowDayOfWeek - 6));
          let weekEndDate = this.formatDate(new Date(nowYear, nowMonth, nowDay - nowDayOfWeek));
          this.formInline.date = [weekStartDate, weekEndDate]
        } else if (val === '本月') {
          let monthStartDate = this.formatDate(new Date(nowYear, nowMonth, 1));
          let monthEndDate = this.formatDate(new Date(nowYear, nowMonth, this.getMonthDays(nowMonth)));
          this.formInline.date = [monthStartDate, monthEndDate]
        }
      }
    },
    computed: {

    },
    created() {
      // 初始化获取数据
      this.formInline.time = '昨日'
      let timer = this.timeForMat(1)
      this.formInline.date = [timer.t2, timer.t1]
      businessuserget({}).then(reD=>{
         if (reD&&reD.buildingInfos&&reD.buildingInfos.length > 0) {
           aggChannelQueryGroup({cityCode: reD.buildingInfos[0].cityCode}).then(res=>{
              if (res.list) {
                this.realEstateList = res.list
              } else {
                this.realEstateList = []
              }
            }).catch(err=>{
              this.$Message.error(err)
            })
         } else {
           aggChannelQueryGroup().then(res=>{
              if (res.list) {
                this.realEstateList = res.list
              } else {
                this.realEstateList = []
              }
            }).catch(err=>{
              this.$Message.error(err)
            })
         }
       }).catch(err=>{
         console.log("查询中台用户信息", err)
       })
      userbuildinglist({page: 1, rows: 100}).then(res=>{
        this.buildingIds = []
          if (res && res.list) {
            res.list.map((item)=>{
              this.buildingIds.push(item.buildingId)
            })
            this.initData()
          } else {
            this.initData()
          }
        }).catch(err=>{
          this.$Message.error(err)
        })
    },
    mounted() {
      window.onresize = () => {
        return (() => {
          setTimeout(() => {
            this.onresizeHeight = window.innerHeight - this.$refs.TableHeight.$el.offsetTop - 100
          }, 10);
        })();
      };
    },
    watch: {

    },
  }
</script>
<style lang="scss" scoped>
  .ivu-radio-group-button .ivu-radio-wrapper-checked{
      background-color: #2d8cf0 !important;
      color: #fff;
    }
  .personalClueDataStyle{
    padding: 10px 14px;
    .formStyle{
      margin-bottom: 20px;
    }
    .spanMarginRL{
      margin: 0px 6px 0px 30px;
    }
    .spanMargin{
      margin: 0px 6px 0px 0px;
    }
    /* page */
    .pagePublicStyle {
      width: 100%;
      margin: 14px 0;
      height: 32px;
      .totalCount {
        position: absolute;
        height: 32px;
        line-height: 32px;
        display: inline-block;
        vertical-align: top;
        color: #657180;
      }
      .pager {
        display: inline-block;
        vertical-align: top;
        position: absolute;
        right: 20px;
        background-color: #fff;
        padding-left: 50px;
      }
    }
  }
</style>
